package com.gzx.risk.core.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class CommonWechatUtil {

    private static final String URL_SEND_BASE = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=";
    private static final String URL_UPLOAD_MEDIA = "https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=";

    /**
     * 企微通知：markdown
     */
    public static void sendMessageTool(WechatBotKeyEnum wechatBotKeyEnum, WechatNotificationType type, String title,
                                       List<String> noticeUserList, List<String> contents) {
        Map<String, Object> body = new HashMap<>();
        body.put("msgtype", "markdown");
        StringBuilder markdownContent = new StringBuilder("#".repeat(type.getTitleLevel()) + " " + title + "\n\n\n\n");
        for (String content:contents) {
            markdownContent.append("<font color=\"").append(type.getColor()).append("\">").append(content).append("</font>\n\n\n\n");
        }
        for (String user : noticeUserList) {
            markdownContent.append("<@").append(user).append("> ");
        }
        body.put("markdown", Map.of("content", markdownContent.toString()));
        String url = URL_SEND_BASE + wechatBotKeyEnum.getKey();
        post(url, null, JSON.toJSONString(body));
    }

    public static void sendImageTool(WechatBotKeyEnum botKeyEnum,InputStream fileStream) throws Exception {
        Map<String, Object> body = new HashMap<>();
        body.put("msgtype", "image");
        Map<String, String> fileMap = new HashMap<>();
        byte[] bytes = DataConvertUtils.inputStreamToBytes(fileStream);
        fileMap.put("base64", DataConvertUtils.bytesToBase64(bytes));
        fileMap.put("md5", CryptoUtils.bytesToMD5(bytes));
        body.put("image", fileMap);
        String url = URL_SEND_BASE + botKeyEnum.getKey();
        post(url, null, JSONObject.toJSONString(body));
    }

    public static void sendFileTool(WechatBotKeyEnum botKeyEnum,InputStream fileStream, String fileName, String type) throws IOException {
        String uploadMediaUrl = URL_UPLOAD_MEDIA + botKeyEnum.getKey() + "&type="+type;
        String mediaId = uploadMedia(uploadMediaUrl, fileStream, fileName);
        String url = URL_SEND_BASE + botKeyEnum.getKey();
        Map<String, Object> body = new HashMap<>();
        body.put("msgtype", type);
        Map<String, String> fileMap = new HashMap<>();
        fileMap.put("media_id", mediaId);
        body.put("image", fileMap);
        post(url, null, JSONObject.toJSONString(body));
    }

    private static String post(String url, Map<String, Object> headerMap, String bodyStr) {
        HttpRequest post = HttpUtil.createPost(url);
        // 设定请求头
        post.header(Header.CONTENT_TYPE, "application/json");
        if (CollectionUtil.isNotEmpty(headerMap)) {
            for (Map.Entry<String, Object> entry : headerMap.entrySet()) {
                post.header(entry.getKey(), entry.getValue().toString());
            }
        }
        post.body(bodyStr);
        //设置超时时间为5秒
        post.timeout(5000);
        HttpResponse execute = post.execute();
        String respBody = execute.body();
        int statusCode = execute.getStatus();
        if (statusCode == 200) {
            return respBody;
        } else {
            return null;
        }
    }

    private static String uploadMedia(String url, InputStream fileStream, String fileName) throws IOException {
        HttpRequest post = HttpUtil.createPost(url);
        byte[] bytes =inputStreamToBytes(fileStream);
//        post.header(Header.CONTENT_TYPE, "multipart/form-data");
        post.form("media",bytes,fileName);
        post.timeout(5000);
        HttpResponse execute = post.execute();
        String respBody = execute.body();
        int statusCode = execute.getStatus();
        if (statusCode == 200) {
            JSONObject result = JSONObject.parseObject(respBody);
            Integer errcode = result.getInteger("errcode");
            if (errcode != null && errcode == 0) {
                return result.getString("media_id");
            } else {
                log.error("企业微信API返回错误: {}", respBody);
                return "";
            }
        } else {
            log.error("uploadMedia HTTP错误, 状态码: {}", statusCode);
            return "";
        }
    }

    /**
     * 将 InputStream 转换为 byte 数组的正确实现
     */
    private static byte[] inputStreamToBytes(InputStream inputStream) throws IOException {
        try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
            int nRead;
            byte[] data = new byte[1024];
            while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            buffer.flush();
            return buffer.toByteArray();
        }
    }
}
